package l1j.opqlo.C_ItemUse_PART2;

//import java.sql.Connection;
//import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.NewSystem.各項記錄輸出;
import l1j.opqlo.NewSystem.ItemLevelUp.ItemLevelUpTable;
import l1j.opqlo.防暴等措施.快速50級;
//import l1j.server.DatabaseFactory;
import l1j.server.echo.ClientThread;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.datatables.lock.AccountReading;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1PcInventory;
import l1j.server.server.model.L1Quest;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_OwnCharStatus;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.serverpackets.S_SkillSound;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.templates.L1Account;

//import l1j.server.server.utils.SQLUtil;

public class C_opqloSpecial {

	private static final Logger _log = Logger.getLogger(C_opqloSpecial.class
			.getName());

	/** 支票換金幣 BY opqlo */
	public static void CheckToMoney(L1ItemInstance l1iteminstance,
			L1PcInstance pc) {
		if (l1iteminstance.getCount() > 0 && l1iteminstance != null) {
			final L1ItemInstance l1iteminstance2 = pc.getInventory()
					.findItemId(40308);
			if (l1iteminstance2 != null) {
				final long MoneyCount = l1iteminstance2.getCount();
				if (MoneyCount < 0 || MoneyCount >= 1900000000) {
					pc.sendPackets(new S_ServerMessage(166, "金幣不能超過【１９億】"));
					return;
				}
			}
			if (createNewItem(pc, 40308, 100000000) != null) {
				pc.getInventory().removeItem(l1iteminstance, 1);
				// TODO 使用物品記錄by opqlo
				StringBuilder aa = new StringBuilder(32)
						.append(pc.getNetConnection().getIp().toString())
						.append(" IP ").append(pc.getName()).append("身上金條（")
						.append(l1iteminstance.getCount()).append("）時間: (")
						.append(new Timestamp(System.currentTimeMillis()))
						.append(")");
				各項記錄輸出.LogSave(12, aa.toString());
				aa.delete(0, aa.length());
				aa = null;
				// TODO 使用物品記錄by opqlo
			}
		}
	}

	private static L1ItemInstance createNewItem(final L1PcInstance pc,
			final int item_id, final int count) {
		final L1ItemInstance item = ItemTable.getInstance().createItem(item_id);
		if (item != null) {
			item.setCount(count);
			if (pc.getInventory().checkAddItem(item, count) == L1Inventory.OK) {
				pc.getInventory().storeItem(item);
				pc.sendPackets(new S_ServerMessage(403, item.getLogName())); // %0を手に入れました。
			} else { // 持てない場合は地面に落とす 處理のキャンセルはしない（不正防止）
				// L1World.getInstance().getInventory(pc.getX(), pc.getY(),
				// pc.getMapId()).storeItem(item);
				return null;
			}
			return item;
		}
		return null;
	}

	/** 金幣換支票 BY opqlo */
	public static void MoneyToCheck(L1ItemInstance l1iteminstance,
			L1PcInstance pc) {
		if (l1iteminstance.getCount() >= 100000001
				&& l1iteminstance.getCount() > 0
				&& l1iteminstance.getCount() < 2000000001) {
			if (createNewItem(pc, 60308, 1) != null) {
				pc.getInventory().removeItem(l1iteminstance, 100000000);// 扣除1億金幣
				final StringBuilder aa = new StringBuilder(32)
						.append(pc.getNetConnection().getIp().toString())
						.append(" IP ").append(pc.getName()).append("身上金幣（")
						.append(l1iteminstance.getCount()).append("）時間: (")
						.append(new Timestamp(System.currentTimeMillis()))
						.append(")");
				各項記錄輸出.LogSave(11, aa.toString());
				aa.delete(0, aa.length());
				// TODO 使用物品記錄by opqlo
			}
		} else {
			pc.sendPackets(new S_ServerMessage(166, "金幣至少超過【１億】"));
		}
	}

	public static void PassWorldChange(final ClientThread client) {

		final L1Account account = client.getAccount();
		account.set_password(null);
		account.set_NoUncodePSW(null);
		AccountReading.get().updatePwd(account.get_login(), null, null);
		// String name = client.getAccountName();
		_log.info(client.getAccountName() + " 更改密碼後中斷連線。");
		client.close();
		// try {
		// Thread.sleep(300);
		// } catch (InterruptedException e) {
		// _log.log(Level.SEVERE , e.getLocalizedMessage() , e);
		// }

		// Connection connection = null;
		// PreparedStatement preparedstatement = null;
		// try {
		// connection = DatabaseFactory.get().getConnection();
		// preparedstatement =
		// connection.prepareStatement("DELETE FROM accounts WHERE login=?");
		// preparedstatement.setString(1, name );
		// preparedstatement.execute();
		// } catch (Exception e) {
		// _log.log(Level.SEVERE , e.getLocalizedMessage() , e);
		// } finally{
		// SQLUtil.close(connection);
		// SQLUtil.close(preparedstatement);
		// }
		// 密碼修改卷軸
	}

	/**
	 * 轉生藥水&&自殺藥水 BY opqlo
	 *
	 * @throws Exception
	 */
	public static void Reincarnation(final L1ItemInstance l1iteminstance,
			final L1PcInstance pc) throws Exception {
		final int itemid = l1iteminstance.getItemId();
		final S_SkillSound ss = new S_SkillSound(pc.getId(), 3393);

		if (itemid == 43000) {
			int levelmet = pc.get_metempsychosis();
			if (levelmet < 200) {
				// pc.getInventory().takeoffEquip(945);// TODO 用來脫掉全身裝備

				if (pc.getLevel() == 99) {
					if(levelmet>=150 && pc.getExp() <0x6ECF16D0){
						pc.sendPackets(new S_SystemMessage("150轉以上，轉生需要經驗達100%。"));
						return;
					}
					try {
						L1Teleport.teleport(pc, l1iteminstance.getItem()
								.get_locx(), l1iteminstance.getItem()
								.get_locy(), l1iteminstance.getItem()
								.get_mapid(), 5, true);
						RemoveEquip(pc.getInventory());// opqlo 用來脫掉全身裝備
						pc.setExp(1);
						if (pc.get_metempsychosis() <= 30) {
							快速50級.get().set(pc);
						}
						pc.resetLevel();
						// TODO 血量調整
						/*
						 * switch (Config.REVIVAL_POTION) { case 1:
						 * pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.9D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.9D))); break; case
						 * 2: pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.8D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.8D))); break; case
						 * 3: pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.7D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.7D))); break; case
						 * 4: pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.6D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.6D))); break; case
						 * 5: pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.5D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.5D))); break; case
						 * 6: pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.4D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.4D))); break; case
						 * 7: pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.3D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.3D))); break; case
						 * 8: pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.2D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.2D))); break; case
						 * 9: pc.addBaseMaxHp((short) (-1 * (int)
						 * (pc.getBaseMaxHp() * 0.1D))); pc.addBaseMaxMp((short)
						 * (-1 * (int) (pc.getBaseMaxMp() * 0.1D))); break; }
						 */
						L1ItemInstance item = pc.getInventory().findItemId(
								810004);// pc.getInventory().checkItem(810004);
						if (item == null) {
							item = ItemTable.getInstance().createItem(810004);
							item.setCount(1);
							item.setIdentified(true);
							pc.getInventory().storeItem(item);
							pc.sendPackets(new S_ServerMessage(403, item
									.getLogName())); // %0を手に入れました。
						}
						levelmet++;
						item.setLevel(levelmet);
						ItemLevelUpTable.getInstance().getLevelStatus(item);
						pc.getInventory().updateItem(item,
								L1PcInventory.COL_LEVEL);
						pc.getInventory().saveItem(item,
								L1PcInventory.COL_LEVEL);
						pc.getInventory().removeItem(l1iteminstance, 1);
						pc.set_metempsychosis(levelmet);// TODO 轉生次數+1
						// TODO 血量調整
						// TODO 防禦、魔防、命中、攻擊重新計算
						pc.resetBaseAc();
						pc.resetBaseMr();
						pc.resetBaseHitup();
						pc.resetBaseDmgup();
						// TODO 防禦、魔防、命中、攻擊重新計算
						pc.setBonusStats(0);
						pc.save(); // DBにキャラクター情報を書き迂む
						pc.sendPackets(new S_OwnCharStatus(pc));
						pc.sendPackets(ss);
						pc.broadcastPacketAll(ss);
						pc.sendPackets(new S_ServerMessage(822)); // 獨自アイテムですので、メッセージは適當です。。
						// L1World.getInstance().broadcastPacketToAll(pc , new
						// S_SystemMessage("\\fY公告：恭喜【" + pc.getName() +
						// "】喝下轉生藥水\\fY第【" + levelmet + "】次轉生囉"));
						pc.sendPackets(new S_SystemMessage("\\fY恭喜你第【"
								+ levelmet + "】次轉生囉。"));
					} catch (final Exception e) {
						_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
					}
				}
			} else {
				pc.sendPackets(new S_SystemMessage("你的根基已達到頂峰。"));
			}
		} else if (itemid == 240105) {
			if (pc.getLevel() <= 10 || pc.get_metempsychosis() > 0) {
				pc.sendPackets(new S_ServerMessage(79));
				return;
			}
			if (pc.getQuest().get_step(L1Quest.QUEST_opqlo_自殺藥水) > 0) {
				pc.sendPackets(new S_SystemMessage("每個角色只能使用一次。"));
				return;
			}
			RemoveEquip(pc.getInventory());// opqlo 用來脫掉全身裝備
			pc.getInventory().removeItem(l1iteminstance, 1);
			// pc.getInventory().takeoffEquip(945);//TODO 用來脫掉全身裝備
			快速50級.get().自殺藥水(pc);
			pc.resetLevel();
			pc.addBaseMaxHp((short) (-1 * (int) ((double) pc.getBaseMaxHp() - 12)));
			pc.addBaseMaxMp((short) (-1 * (int) ((double) pc.getBaseMaxMp() - 12)));
			pc.resetBaseAc();
			pc.resetBaseMr();
			pc.resetBaseHitup();
			pc.resetBaseDmgup();
			pc.getQuest().set_step(L1Quest.QUEST_opqlo_自殺藥水, 255);
			L1Teleport.teleport(pc, l1iteminstance.getItem().get_locx(),
					l1iteminstance.getItem().get_locy(), l1iteminstance
							.getItem().get_mapid(), 5, true);
			pc.save(); // DBにキャラクター情報を書き迂む
			pc.sendPackets(new S_OwnCharStatus(pc));
			pc.sendPackets(new S_ServerMessage(822));
			pc.sendPackets(ss);
			pc.broadcastPacketAll(ss);
			// L1World.getInstance().broadcastPacketToAll(pc , new
			// S_SystemMessage("\\fV玩家【" + pc.getName()+ "】在極大的痛苦中感到精神甦醒"));
		}
	}

	private static void RemoveEquip(L1PcInventory inventory) {

		for (final L1ItemInstance item : inventory.getItems()) {
			if (item.isEquipped()) {
				inventory.setEquipped(item, false, false, false);
			}
		}
	}
}
